package com.zhangyu.shadow.repair.delegate.repair;

import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rey.material.app.DatePickerDialog;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.ThemeManager;
import com.rey.material.app.TimePickerDialog;
import com.zhangyu.shadow.repair.R;
import com.zhangyu.shadow.repair.R2;
import com.zhangyu.shadow.repair.config.RepairItemType;
import com.zhangyu.shadow.repair.config.StateCode;
import com.zhangyu.shadow.repair.delegate.maintain.MaintainDataConverter;
import com.zhangyu.shadow.repair.delegate.repair.entity.Level0Item;
import com.zhangyu.shadow.repair.delegate.repair.entity.Level1Item;
import com.zhangyu.shadow.repair.delegate.search.entity.MaintainEntity;
import com.zhangyu.shadow.repair.event.TroubleAddEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import st.lib.base.delegate.RxShadowDelegate;
import st.lib.base.ui.progress.sweetalert.DialogLoader;
import st.lib.base.ui.recycler.MultipleItemEntity;

/**
 * @author zhangyu
 * @date 2018/2/13
 */

public class RepairDelegate extends RxShadowDelegate {
    private static final String ENTITY = "entity";
    private DialogLoader mDialogLoader;

    public static RepairDelegate create(MultipleItemEntity entity) {
        final RepairDelegate contentDelegate = new RepairDelegate();
        final Bundle bundle = new Bundle();
        bundle.putSerializable(ENTITY, entity);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.tv_repair_date)
    TextView mTvRepairDate;
    @BindView(R2.id.tv_factory_date)
    TextView mTvFactoryDate;
    @BindView(R2.id.tv_repair_time)
    TextView mTvRepairTime;
    @BindView(R2.id.tv_factory_time)
    TextView mTvFactoryTime;
    @BindView(R2.id.tv_out_date)
    TextView mTvOutDate;
    @BindView(R2.id.tv_out_time)
    TextView mTvOutTime;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.layout_out_time)
    LinearLayout mLayoutOutTime;
    @BindView(R2.id.button_confirm)
    Button mBtnConfirm;
    @BindView(R2.id.tv_bus_number)
    TextView mTvBusNumber;
    @BindView(R2.id.tv_person)
    TextView mTvPerson;
    private ExpandableItemAdapter mItemAdapter;
    private MaintainEntity mItemEntity;
    private String mState;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle bundle = getArguments();
        if (bundle != null) {
            MultipleItemEntity multipleItemEntity = (MultipleItemEntity) bundle.getSerializable(ENTITY);
            mItemEntity = multipleItemEntity != null ?
                    (MaintainEntity) multipleItemEntity.getField(RepairItemType.ITEM_REPAIR) : null;
            mState = mItemEntity != null ? mItemEntity.getWorkStatusCode() : null;
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_repair_input;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        initView();
    }

    private void initView() {
        setViewState(mState);
        mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        if (mItemEntity != null) {
            mTvBusNumber.setText(mItemEntity.getVehicleCode());
            mItemAdapter = new ExpandableItemAdapter(this, new MaintainDataConverter()
                    .converter(mItemEntity.getWorkStatusCode(), mItemEntity.getListClassification()));
            mTvPerson.setText(mItemEntity.getReportPersonName());
        }
        mRecyclerView.setAdapter(mItemAdapter);
        mItemAdapter.expandAll();

        EventBus.getDefault().register(this);

    }

    private void setViewState(String type) {
        try {
            switch (type) {
                case StateCode.FINISH_PLAN:
                    mToolbar.setTitle(mItemEntity.getVehicleCode() + "    报修登记");
                    mBtnConfirm.setText("打卡确认");
                    mLayoutOutTime.setVisibility(View.INVISIBLE);
                    String[] repairDateTime = getNowDateTime();
                    mTvRepairDate.setText(repairDateTime[0]);
                    mTvRepairTime.setText(repairDateTime[1]);
                    mTvFactoryDate.setText(repairDateTime[0]);
                    mTvFactoryTime.setText(repairDateTime[1]);
                    break;
                case StateCode.READY_WORK:
                    mBtnConfirm.setText("已登记");
                    mBtnConfirm.setEnabled(false);
                    mLayoutOutTime.setVisibility(View.INVISIBLE);
                    setDateTimeState();
                case StateCode.UNDER_WORK:
                    mBtnConfirm.setText("处理中");
                    mBtnConfirm.setEnabled(false);
                    mLayoutOutTime.setVisibility(View.INVISIBLE);
                    setDateTimeState();
                    break;
                case StateCode.COMPLETED_WORK:
                    mLayoutOutTime.setVisibility(View.VISIBLE);
                    mBtnConfirm.setText("确认交车");
                    String[] outDateTime = getNowDateTime();
                    mTvOutDate.setText(outDateTime[0]);
                    mTvOutTime.setText(outDateTime[1]);
                    setDateTimeState();
                    break;
                case StateCode.FINISH_WORK:
                    mBtnConfirm.setText("已交车");
                    mLayoutOutTime.setVisibility(View.VISIBLE);
                    mTvOutDate.setEnabled(false);
                    mTvOutTime.setEnabled(false);
                    mBtnConfirm.setEnabled(false);
                    mTvOutDate.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    mTvOutTime.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    String outTime = mItemEntity.getOutFactoryTime();
                    String[] OutDateTime = outTime.split(" ");
                    mTvOutDate.setText(OutDateTime[0]);
                    mTvOutTime.setText(OutDateTime[1]);

                    setDateTimeState();
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String[] getNowDateTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String dateString = simpleDateFormat.format(new Date());
        return dateString.split(" ");
    }


    private void setDateTimeState() {
        mToolbar.setTitle(mItemEntity.getVehicleCode() + "    报修详情");
        String repairTime = mItemEntity.getTroubleTime();
        String[] repairDateTime = repairTime.split(" ");
        String factoryTime = mItemEntity.getInFactoryTime();
        String[] factoryDateTime = factoryTime.split(" ");

        mTvRepairDate.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        mTvRepairDate.setEnabled(false);
        mTvRepairDate.setText(repairDateTime[0]);
        mTvRepairTime.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        mTvRepairTime.setEnabled(false);
        mTvRepairTime.setText(repairDateTime[1]);
        mTvFactoryDate.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        mTvFactoryDate.setEnabled(false);
        mTvFactoryDate.setText(factoryDateTime[0]);
        mTvFactoryTime.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        mTvFactoryTime.setEnabled(false);
        mTvFactoryTime.setText(factoryDateTime[1]);
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @OnClick({R2.id.tv_repair_date, R2.id.tv_repair_time,
            R2.id.tv_factory_date, R2.id.tv_factory_time,
            R2.id.tv_out_date, R2.id.tv_out_time})
    public void onRepairDateClick(View view) {
        Dialog.Builder builder;
        boolean isLightTheme = ThemeManager.getInstance().getCurrentTheme() == 0;
        final int id = view.getId();
        if (id == R.id.tv_repair_date || id == R.id.tv_factory_date || id == R.id.tv_out_date) {
            builder = new DatePickerDialog.Builder(isLightTheme ? R.style.Material_App_Dialog_DatePicker_Light : R.style.Material_App_Dialog_DatePicker) {
                @Override
                public void onPositiveActionClicked(DialogFragment fragment) {
                    DatePickerDialog dialog = (DatePickerDialog) fragment.getDialog();
                    String date = dialog.getFormattedDate(new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA));
                    if (id == R.id.tv_repair_date) {
                        mTvRepairDate.setText(date);
                    } else if (id == R.id.tv_factory_date) {
                        mTvFactoryDate.setText(date);
                    } else {
                        mTvOutDate.setText(date);
                    }
                    super.onPositiveActionClicked(fragment);
                }

                @Override
                public void onNegativeActionClicked(DialogFragment fragment) {
                    super.onNegativeActionClicked(fragment);
                }
            };
        } else {
            builder = new TimePickerDialog.Builder(isLightTheme ? R.style.Material_App_Dialog_TimePicker_Light : R.style.Material_App_Dialog_TimePicker, 24, 00) {
                @Override
                public void onPositiveActionClicked(DialogFragment fragment) {
                    TimePickerDialog dialog = (TimePickerDialog) fragment.getDialog();
                    String time = dialog.getFormattedTime(new SimpleDateFormat("HH:mm", Locale.CHINA));
                    if (id == R.id.tv_repair_time) {
                        mTvRepairTime.setText(time);
                    } else if (id == R.id.tv_factory_time) {
                        mTvFactoryTime.setText(time);
                    } else {
                        mTvOutTime.setText(time);
                    }
                    super.onPositiveActionClicked(fragment);
                }

                @Override
                public void onNegativeActionClicked(DialogFragment fragment) {
                    super.onNegativeActionClicked(fragment);
                }
            };
        }

        builder.positiveAction("确定")
                .negativeAction("取消")
        ;
        DialogFragment fragment = DialogFragment.newInstance(builder);
        fragment.show(getChildFragmentManager(), null);
    }

    @Subscribe
    public void onTroubleAddEvent(TroubleAddEvent event) {
        int position = event.mPosition;
        List<MultipleItemEntity> list = event.mItemEntities;
        final Level0Item lv0 = (Level0Item) mItemAdapter.getItem(position);
        ArrayList<Level1Item> level1Items = new ArrayList<>();
        level1Items.add(new Level1Item(list));
        if (lv0 != null) {
            lv0.setSubItems(level1Items);
        }

        final Level1Item lv1 = (Level1Item) mItemAdapter.getItem(position + 1);
        if (lv1 != null) {
            lv1.setMultiItemEntities(list);
        }

        mItemAdapter.notifyItemChanged(position);
        mItemAdapter.notifyItemChanged(position + 1);
    }

    @OnClick(R2.id.button_confirm)
    public void onConfirm() {

        if (mDialogLoader == null) {
            mDialogLoader = new DialogLoader(getContext());
        }
        mDialogLoader.showProgressDialog(true, "初始化设备...", "");

    }

}



